/**
 * Created by jeryzym on 2017/6/30.
 */
define(['knockout',
    'platform.common',
    'bootbox',
    'knockout-bsTable',
    'knockout-jsTree',
    'knockout-component',
    'bootstrapValidator',
    'bootstrapValidator-zhCN',
    'sco.msg'], function (ko, platform, bootbox) {

    var rest = {
        get: function (id) {
            var param = {};
            param.user_id = id;
            var result = platform.servicebreak('~/rest/user/selectOne', param).responseJSON;
            return result;
        },
        remove: function (param) {
            platform.servicebreakAsync('~/rest/user/delete', param, 'post')
                .done(function (response) {
                    if (response instanceof Object && response.meta.success) {
                        platform.showOperTip('DELSUC');
                        viewModel.tableViewModel.refresh({org_id:viewModel.selectedNode});
                    }
                });
        },
        save: function (param) {
            platform.servicebreakAsync('~/rest/user/save', param, 'post',
                function () {
                    platform.showOperTip('dealing');
                }).done(function (response) {
                if (response instanceof Object && response.meta.success) {
                    platform.showOperTip('SAVESUC');
                    viewModel.tableViewModel.refresh();
                }
            }).fail(function () {
                platform.showOperTip("savefail");
            });
        }
    };
    var kbTable = require('knockout-bsTable');
    var jsTree = require('knockout-jsTree');

    var ViewModel = function () {
        var self = this;
        self.modalVisible = ko.observable(false);
        self.columns = [
            {
                checkbox: true,
                align: 'center',
                width: 30
            }, {
                field: 'display_order',
                title: '序号',
                formatter: function (value, row, index) {
                    var options = self.tableViewModel.getOptions();
                    var indexPageNum = parseInt(options.pageNumber);
                    var indexPageSize = parseInt(options.pageSize);
                    return ((indexPageNum - 1) * indexPageSize)
                        + (index + 1);
                },
                width: 35,
                align: 'center'
            }, {
                field: 'user_id',
                title: '主键标识',
                align: 'left',
                visible: false
            }, {
                field: 'user_name',
                title: '用户名',
                width: 120
            }, {
                field: 'nick_name',
                title: '显示名称',
                width: 200
            }, {
                field: 'effective_date',
                title: '生效日期',
                width: 180
            }, {
                field: 'expire_date',
                title: '失效日期'
            }, {
                field: 'org_id',
                title: '所属组织机构标识',
                visible: false
            }];
        self.tableViewModel = new kbTable.bootstrapTableViewModel({
            url: platform.mapUrl('~/rest/user/list'),
            toolbar: '#toolbar',
            queryParams: function (params) {
                return {
                    pageNumber: params.offset / params.limit + 1,
                    pageSize: params.limit,
                    org_id: ''
                };
            },
            columns: self.columns
        });
        self.treeViewModel = new jsTree.jsTreeViewModel({
            core: {
                data: {
                    url: platform.mapUrl('~/rest/org/loadOrgTreeNodes'),
                    dataType: 'json',
                    method: 'post'
                }
            }
        });
        self.selectedNode = ko.observable();
        self.nodesAttributes = {};
        self.onTreeNodeSelected = function (event, data) {
            var param = {};
            if (data.node.parent == '#') {
                param.org_id = '';
                self.selectedNode('');
                self.nodesAttributes = {};
            } else {
                param.org_id = data.node.id;
                self.selectedNode(data.node.id);
                self.nodesAttributes = data.node.original.attributes;
            }
            self.tableViewModel.refresh(param);
        };
        self.userViewModel = {
            title: ko.observable(),//对话框标题
            userId: ko.observable(),//用户ID
            userName: ko.observable(),//用户名
            nickName: ko.observable(),//昵称
            userPwd: ko.observable(),//用户密码
            editStatus: ko.observable(),//编辑状态
            recordStatus: ko.observable(),//数据状态
            orgId: ko.observable(),//所属组织机构
            enabled: ko.observable(true),
            visibled: ko.observable(true),
            resetForm: function () {//重置表单
                $('#detailForm').resetForm();

                if ($('#detailForm').data('bootstrapValidator') != null ||
                    $('#detailForm').data('bootstrapValidator') != undefined) {
                    $('#detailForm').data('bootstrapValidator').resetForm();
                }

                this.title('');
                this.userId('');
                this.userName('');
                this.nickName('');
                this.userPwd('');
                this.editStatus('0');
                this.recordStatus('1');
                this.orgId('');
                this.enabled(true);
            },
            disableForm: function () {
                $('#detailForm').find('input,textarea').attr('disabled', true);
            },
            enableForm: function () {
                $('#detailForm').find('input,textarea').attr('disabled', false);
            },
            setFormData: function (id) {
                var result = rest.get(id);
                if (result instanceof Object && result.meta.success) {
                    var info = result.responseObject;
                    this.userId(info.user_id);
                    this.userName(info.user_name);
                    this.nickName(info.nick_name);
                }
            },
            validateForm: function () {
                $('#detailForm').bootstrapValidator({
                    message: 'This value is not valid',
                    feedbackIcons: {
                        valid: 'glyphicon glyphicon-ok',
                        invalid: 'glyphicon glyphicon-remove',
                        validating: 'glyphicon glyphicon-refresh'
                    },
                    excluded: [':disabled'],
                    fields: {
                        userName: {
                            validators: {
                                notEmpty: {
                                    message: '用户名称为必填字段,不可为空'
                                },
                                stringLength: {
                                    min: 5,
                                    max: 12,
                                    message: '用户名长度限制在5-12位之间'
                                },
                                regexp: {
                                    /* 只需加此键值对，包含正则表达式，和提示 */
                                    regexp: /^[a-zA-Z0-9\.]+$/,
                                    message: '只能是数字、字母.'
                                },
                                remote: { // onchange校验，不太实用，频繁调用，可用性差，此处保留仅作为测验，可通过使用光标离开事件替代
                                    url: platform.mapUrl('~/rest/user/validate'),
                                    message: '检测到用户名已存在',
                                    type: 'post'
                                }
                            }
                        },
                        nickName: {
                            validators: {
                                notEmpty: {
                                    message: '用户昵称为必填字段,不可为空'
                                }
                            }
                        },
                        userPwd: {
                            validators: {
                                notEmpty: {
                                    message: '密码为必填字段,不可为空'
                                },
                                stringLength: {
                                    min: 6,
                                    max: 12,
                                    message: '密码长度应该控制在6-12位之间'
                                }
                            }
                        }
                    }
                });
            },
            showNewForm: function () {
                this.resetForm();
                this.validateForm();
                this.enableForm();

                this.title('新增账户信息');
                this.userId(platform.uuid());
                this.orgId(self.selectedNode());
                this.editStatus('0');
                this.recordStatus('1');
                self.modalVisible(true);
            },
            showEditForm: function (id) {
                this.resetForm();
                this.validateForm();
                this.enableForm();

                this.title('编辑账户信息');
                this.setFormData(id);
                self.modalVisible(true);
            },
            showViewForm: function (id) {
                this.resetForm();
                this.disableForm();

                this.visibled(false);
                this.title('查看账户信息');
                this.setFormData(id);
                this.enabled(false);
                self.modalVisible(true);
            },
            save: function () {
                //验证first
                $('#detailForm').data('bootstrapValidator').validate();
                if (!$('#detailForm').data('bootstrapValidator').isValid()) {
                    platform.showOperTip('VALIDATEFAIL');
                    return;
                }

                var param = {};
                param.user_id = this.userId();
                param.user_name = this.userName();

                param.edit_status = this.editStatus();
                if (param.edit_status == '0') {
                    param.nick_name = this.nickName();
                    param.user_pwd = this.userPwd();
                    param.record_status = this.recordStatus();
                    param.org_id = this.orgId();
                }

                rest.save(param);
            },
            close: function () {
                self.modalVisible(false);
                $('#userDialog').toggleClass('hide');
            }
        };
        /**
         * methodName:fnAdd
         * description:新增方法
         */
        self.fnAdd = function () {
            //判断组织机构树选择的是否为部门
            if (self.nodesAttributes.org_type != null && self.nodesAttributes.org_type === '1') {
                self.userViewModel.showNewForm();
                $('#userDialog').toggleClass('hide');
            } else {
                platform.showWarnTip('请选择级别为部门的组织单元后进行人员新增操作!');
            }
        };
        /**
         * methodName:fnEdit
         * description:修改方法
         */
        self.fnEdit = function () {
            var selections = self.tableViewModel.getSelections();
            if (selections.length == 1) {
                self.userViewModel.showEditForm(selections[0].user_id);
                $('#userDialog').toggleClass('hide');
            } else {
                platform.showTip('EDIT');

            }
        };
        /**
         * methodName:fnView
         * description:查看方法
         */
        self.fnView = function () {
            var selections = self.tableViewModel.getSelections();
            if (selections.length == 1) {
                self.userViewModel.showViewForm(selections[0].user_id);
                $('#userDialog').toggleClass('hide');
            } else {
                platform.showTip('VIEW');

            }
        };
        /**
         * methodName:fnRemove
         * description:删除方法
         */
        self.fnRemove = function () {
            var selections = self.tableViewModel.getSelections();
            if (selections.length == 1) {
                bootbox.confirm({
                    title: '删除提示',
                    size: 'small',
                    message: '是否删除该数据?',
                    buttons: {
                        confirm: {
                            label: '确认',
                            className: 'btn-success btn-sm'
                        },
                        cancel: {
                            label: '取消',
                            className: 'btn-default btn-sm'
                        }
                    },
                    callback: function (result) {
                        if (result) {
                            var param = {};
                            param.user_id = selections[0].user_id;
                            param.user_name = selections[0].user_name;
                            rest.remove(param);
                        }
                    }
                });
            } else {
                platform.showTip('REMOVE');

            }
        };
        /**
         * methodName:fnRemove
         * description:删除方法
         */
        self.fnSearch = function () {

        }
    };
    var viewModel = new ViewModel();
    return viewModel;
});